package com.resttest.ljs.controller;

import com.resttest.ljs.entity.Stu;
import com.resttest.ljs.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/rabbit")
public class RabbitConsumer {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> ex(MethodArgumentNotValidException e){
        String body = null;
        BindingResult bindingResult=e.getBindingResult();
        if(bindingResult.hasErrors()){
            List<ObjectError> allError = bindingResult.getAllErrors();
            if(!allError.isEmpty()){
                ObjectError objectError = allError.get(0);
                if(objectError instanceof FieldError){
                    FieldError fieldError =(FieldError) objectError;
                    //body = CommonResponse.error
                }
            }
        }
        if(body == null || body.equals("")){
            body = "";
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>(body,headers, HttpStatus.UNAUTHORIZED);
    }

    @PostMapping(value = "/ceshi")
    public String Consumer(@RequestBody @Valid Stu stu, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return bindingResult.getAllErrors().get(0).getDefaultMessage();
        }
        log.info("响应报文："+stu.getName()+"当前时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
        return   "响应报文："+stu.getName()+"当前时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
    }
}
